using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;


namespace RelationTextBox
{
    public delegate void MyButtonClickHandler(object sender, DataGridViewCellEventArgs args);
    public class DataGridViewRelationTextBoxCell : DataGridViewTextBoxCell
    {
        private EventHandler _MyButtonClick = null;
        public EventHandler MyButtonClick
        {
            get { return _MyButtonClick; }
            set 
            { 
                _MyButtonClick = value;
                if (ctl != null)
                    ctl.ButtonClick += _MyButtonClick;
            }
        }
        // The bitmap used to paint the non-edited cells via a call to NumericUpDown.DrawToBitmap
        [ThreadStatic]
        private static Bitmap renderingBitmap;

        // Default dimensions of the static rendering bitmap used for the painting of the non-edited cells
        private const int DATAGRIDVIEWRELATIONTEXTBOXCELL_defaultRenderingBitmapWidth = 100;
        private const int DATAGRIDVIEWRELATIONTEXTBOXCELL_defaultRenderingBitmapHeight = 22;

        // The NumericUpDown control used to paint the non-edited cells via a call to NumericUpDown.DrawToBitmap
        //[ThreadStatic]
        // a fost static - dar l-am sters
        private  static DataGridViewRelationTextBoxControl ctl=null;
 
        public DataGridViewRelationTextBoxCell()
        {
            // Create a thread specific bitmap used for the painting of the non-edited cells
            if (renderingBitmap == null)
            {
                renderingBitmap = new Bitmap(DATAGRIDVIEWRELATIONTEXTBOXCELL_defaultRenderingBitmapWidth, DATAGRIDVIEWRELATIONTEXTBOXCELL_defaultRenderingBitmapHeight);
            }
            // Create a thread specific NumericUpDown control used for the painting of the non-edited cells
            if (ctl == null)
            {
                ctl = new DataGridViewRelationTextBoxControl();
                // Some properties only need to be set once for the lifetime of the control:
                ctl.BorderStyle = BorderStyle.None;
                ctl.BackColor = Color.Yellow;
                //ctl.Maximum = Decimal.MaxValue / 10;
                //ctl.Minimum = Decimal.MinValue / 10;
                
            }
            this.Style.Format = "";
        }
        public override Type EditType
        {
            get
            {
                return typeof(DataGridViewRelationTextBoxControl);
            }
        }
        public override Type ValueType
        {
            get
            {
                return typeof(string);
            }
        }
        public override Object DefaultNewRowValue
        {
            get
            {
                return null;
            }
        }
        
        /// <summary>
        /// Custom implementation of the PositionEditingControl method called by the DataGridView control when it
        /// needs to relocate and/or resize the editing control.
        /// </summary>
        public override void PositionEditingControl(bool setLocation,
                                            bool setSize,
                                            Rectangle cellBounds,
                                            Rectangle cellClip,
                                            DataGridViewCellStyle cellStyle,
                                            bool singleVerticalBorderAdded,
                                            bool singleHorizontalBorderAdded,
                                            bool isFirstDisplayedColumn,
                                            bool isFirstDisplayedRow)
        {
            Rectangle editingControlBounds = PositionEditingPanel(cellBounds,
                                                        cellClip,
                                                        cellStyle,
                                                        singleVerticalBorderAdded,
                                                        singleHorizontalBorderAdded,
                                                        isFirstDisplayedColumn,
                                                        isFirstDisplayedRow);
            
            this.DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y);
            this.DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height);
        }
        
        /// <summary>
        /// DetachEditingControl este apelata de controlul DataGridView cand se incheie sesiunea de editare
        /// </summary>
        [
            EditorBrowsable(EditorBrowsableState.Advanced)
        ]
        public override void DetachEditingControl()
        {
            DataGridView dataGridView = this.DataGridView;
            if (dataGridView == null || dataGridView.EditingControl == null)
            {
                throw new InvalidOperationException("Cell is detached or its grid has no editing control.");
            }

            RelationTextBox relButton = dataGridView.EditingControl as RelationTextBox;
            if (relButton != null)
            {
                // Editing controls get recycled. Indeed, when a DataGridViewNumericUpDownCell cell gets edited
                // after another DataGridViewNumericUpDownCell cell, the same editing control gets reused for 
                // performance reasons (to avoid an unnecessary control destruction and creation). 
                // Here the undo buffer of the TextBox inside the NumericUpDown control gets cleared to avoid
                // interferences between the editing sessions.
                TextBox textBox = relButton.Controls[0] as TextBox;
                if (textBox != null)
                {
                    textBox.ClearUndo();
                }
                relButton.ButtonClick -= this.MyButtonClick;
            }

            base.DetachEditingControl();
        }
        /*
        /// <summary>
        /// Implementarea functiei GetErrorIconBounds function pentru a desena 
        /// iconita de eroar peste buton.
        /// </summary>
        protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
        {
            const int ButtonsWidth = 16;

            Rectangle errorIconBounds = base.GetErrorIconBounds(graphics, cellStyle, rowIndex);
            if (this.DataGridView.RightToLeft == RightToLeft.Yes)
            {
                errorIconBounds.X = errorIconBounds.Left + ButtonsWidth;
            }
            else
            {
                errorIconBounds.X = errorIconBounds.Left - ButtonsWidth;
            }
            return errorIconBounds;
        }
        /// <summary>
        /// implementarea functiei GetPreferredSize. 
        /// Implementarea foloseste dimensiunea preferata a 
        /// DataGridViewTextBoxCell cell si adauga spatiu pentru buton.
        /// </summary>
        protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
        {
            if (this.DataGridView == null)
            {
                return new Size(-1, -1);
            }

            Size preferredSize = base.GetPreferredSize(graphics, cellStyle, rowIndex, constraintSize);
            if (constraintSize.Width == 0)
            {
                const int ButtonsWidth = 16; // Account for the width of the up/down buttons.
                const int ButtonMargin = 8;  // Account for some blank pixels between the text and buttons.
                preferredSize.Width += ButtonsWidth + ButtonMargin;
            }
            return preferredSize;
        }*/
        /// <summary>
        /// implementarea functiei InitializeEditingControl . Functia este apelata de controlul DataGridView 
        /// la inceputul sesiunii de editare. Se asigura ca proprietatile controlului de editare 
        /// sunt in conformitate cu propritatile celulei.
        /// </summary>
        public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
            RelationTextBox edControl = this.DataGridView.EditingControl as RelationTextBox;
            if (edControl != null)
            {
                edControl.BorderStyle = BorderStyle.None;
                edControl.ButtonClick += this.MyButtonClick;
                string initialFormattedValueStr = initialFormattedValue as string;
                if (initialFormattedValueStr == null)
                {
                    edControl.Text = string.Empty;
                }
                else
                {
                    edControl.Text = initialFormattedValueStr;
                }
            }
        }
        /*/// <summary>
        /// Funtie folosita de celula si coloana pentru translatare
        /// </summary>
        internal static HorizontalAlignment TranslateAlignment(DataGridViewContentAlignment align)
        {
            if ((align & anyRight) != 0)
            {
                return HorizontalAlignment.Right;
            }
            else if ((align & anyCenter) != 0)
            {
                return HorizontalAlignment.Center;
            }
            else
            {
                return HorizontalAlignment.Left;
            }
        }
        
        
        /// <summary>
        /// aceasta metoda trebuie implementata pentru a se copia
        /// proprietatile noi implementate
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            DataGridViewRelationTextBoxCell dataGridViewCell = base.Clone() as DataGridViewRelationTextBoxCell;
            if (dataGridViewCell != null)
            {

            }
            return dataGridViewCell;
        }*/
        

    }
}
